package tech.brick.easysharer.config;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import tech.brick.easysharer.service.ServiceRegistryService;

@Slf4j
@Component
@RequiredArgsConstructor
public class ServiceRegistryListener {

    private final ServiceRegistryService serviceRegistryService;
    @Value("${service.discover.enabled:true}")
    private Boolean serviceDiscoverEnabled;

    /**
     * 应用启动完成后进行服务注册
     */
    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationReady() {
        if (!serviceDiscoverEnabled) {
            return;
        }
        log.info("应用启动完成，开始注册服务...");
        
        // 延迟3秒后注册，确保应用完全启动
        new Thread(() -> {
            try {
                Thread.sleep(3000);
                boolean success = serviceRegistryService.registerService();
                if (success) {
                    log.info("服务注册成功");
                } else {
                    log.error("服务注册失败");
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                log.error("服务注册线程被中断", e);
            }
        }).start();
    }
}
